<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="标准名称" prop="dataStandardName">
        <ns-input v-model="formData.dataStandardName" placeholder="请输入标注名称" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <ns-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="标准类型" prop="type">
        <el-select
          v-model="formData.type"
          clearable
          placeholder="请选择标准类型"
          @change="changeType"
        >
          <el-option label="结构化数据" :value="1" />
          <el-option label="非结构化数据" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="父标准" prop="parentId">
        <el-select
          v-model="formData.parentId"
          clearable
          placeholder="请选择父标准"
          :disabled="formData.type != 0 && formData.type != 1"
          value-on-clear=""
        >
          <el-option
            v-for="(item, index) in standardList"
            :key="index"
            :disabled="item.disabled"
            :label="item.dataStandardName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" clearable placeholder="请选择状态">
          <el-option label="开启" value="1" />
          <el-option label="关闭" value="0" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as StandardsApi from '@/api/dataStandards/standards'
import { Warning } from '@element-plus/icons-vue'
import { handleError } from 'vue'
defineOptions({ name: 'StandardsForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const currentId = ref()
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

const formData = ref({
  id: undefined,
  dataStandardName: undefined,
  remark: undefined,
  type: undefined,
  parentId: undefined,
  status: undefined
})
const formRules = reactive({
  dataStandardName: [{ required: true, message: '标准名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '标准类型不能为空', trigger: ['blur', 'change'] }],
  status: [{ required: true, message: '状态不能为空', trigger: ['blur', 'change'] }]
})
const formRef = ref() // 表单 Ref

const changeType = async (val) => {
  getStandList(currentId.value, val)
  formData.value.parentId = undefined
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  currentId.value = id
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await StandardsApi.dataStandardsGet(id)
      getStandList(id, formData.value.type)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const standardList = ref()
const getStandList = async (id, type) => {
  const { data } = await StandardsApi.dataStandardsPage({
    page: 1,
    pageSize: 10000,
    status: '1',
    type
  })
  standardList.value = data.map((item) => {
    if (item.id === id) {
      item.disabled = true
    } else {
      item.disabled = false
    }
    return item
  })
  console.log('standardList.value', standardList.value)
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (data.parentId == '') {
      data.parentName = ''
    }
    if (formType.value === 'create') {
      await StandardsApi.dataStandardsCreate(data)
      message.success(t('common.createSuccess'))
    } else {
      await StandardsApi.dataStandardsUpdate(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    dataStandardName: undefined,
    remark: undefined,
    type: undefined,
    parentId: undefined,
    status: undefined
  }
  formRef.value?.resetFields()
}

//
// const handleChange = (value) => {
//   if (!value) {
//     formData.value?.parentName = ''
//   } else {
//     formData.value.parentName =
//   }
// }
</script>
